<template>
	<view class="container">
		<!-- 头部标题 -->
		<view class="header">
			<view class="category-path">
				<text class="primary-category">{{category}}</text>
				<text class="path-separator">/</text>
				<text class="secondary-category">{{subcategory}}</text>
			</view>
			<text class="title">规则目录</text>
		</view>
		
		<!-- 排序方式选择器 -->
		<view class="sort-options">
			<text class="sort-label">排序方式:</text>
			<view class="sort-buttons">
				<view class="sort-btn" 
					:class="{active: sortOrder === 'asc'}" 
					@click="changeSortOrder('asc')">
					<text>递增</text>
				</view>
				<view class="sort-btn" 
					:class="{active: sortOrder === 'custom'}" 
					@click="changeSortOrder('custom')">
					<text>自定义</text>
				</view>
			</view>
		</view>
		
		<!-- 规则标题卡片列表 -->
		<view class="tertiary-list">
			<view class="tertiary-card" 
				  v-for="(item, index) in tertiaryList" 
				  :key="index"
				  @click="navigateToDetail(item)"
				  @longpress="startDrag(index)"
				  @touchmove="onTouchMove"
				  @touchend="onTouchEnd"
				  :class="{'is-dragging': dragIndex === index}"
				  :style="{ 
					  background: getCardGradient(),
					  transform: dragIndex === index ? `scale(1.05) translateY(${dragOffset}px)` : '',
					  zIndex: dragIndex === index ? 10 : 1,
					  transition: dragIndex === -1 ? 'transform 0.3s ease' : '',
					  opacity: sortOrder === 'custom' ? 1 : (dragIndex === index ? 0.7 : 1)
				  }">
				<view class="card-content">
					<view class="card-header">
						<view class="card-icon">{{getContentIcon(item.title)}}</view>
						<view class="card-title-wrapper">
							<text class="card-title">{{item.title}}</text>
						</view>
					</view>
					<view class="card-meta">
						<view class="card-tags">
							<text class="card-tag" v-for="(tag, tagIndex) in item.tags" :key="tagIndex">{{tag}}</text>
						</view>
						<text class="card-views">{{item.view_count || 0}}次阅读</text>
					</view>
				</view>
			</view>
			
			<!-- 空状态提示 -->
			<view class="empty-state" v-if="tertiaryList.length === 0">
				<image class="empty-image" src="/static/empty.png" mode="aspectFit"></image>
				<text class="empty-text">暂无相关规则内容</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				category: '', // 一级分类
				subcategory: '', // 二级分类
				tertiaryList: [], // 规则标题列表
				loading: false,
				// 拖拽相关变量
				dragIndex: -1, // 当前拖拽的项索引，-1表示未拖拽
				startY: 0, // 开始拖拽的Y坐标
				dragOffset: 0, // 拖拽偏移量
				isDragging: false, // 是否正在拖拽
				cardHeight: 0, // 卡片高度
				listChanged: false, // 列表是否被更改
				sortOrder: 'asc', // 默认按递增排序
				originalList: [] // 保存原始列表数据
			}
		},
		onLoad(options) {
			console.log('规则标题列表页面接收到的参数:', options);
			
			if (options.category) {
				this.category = decodeURIComponent(options.category);
			}
			
			if (options.subcategory) {
				this.subcategory = decodeURIComponent(options.subcategory);
			}
			
			// 尝试读取保存的排序方式
			try {
				const savedSortOrder = uni.getStorageSync(`sortOrder_${this.category}_${this.subcategory}`);
				if (savedSortOrder) {
					this.sortOrder = savedSortOrder;
				}
			} catch (e) {
				console.error('读取排序方式失败', e);
			}
			
			// 加载规则标题数据
			this.loadRuleList();
		},
		methods: {
			// 加载规则标题列表
			loadRuleList() {
				if (!this.category || !this.subcategory) {
					uni.showToast({
						title: '分类参数缺失',
						icon: 'none'
					});
					return;
				}
				
				this.loading = true;
				uni.showLoading({
					title: '加载中...'
				});
				
				// 调用云对象获取规则标题列表
				(async () => {
					try {
						console.log('开始获取规则列表，参数：', {
						category: this.category,
						subcategory: this.subcategory
						});
						
						const learningService = uniCloud.importObject('learning-service');
						const res = await learningService.getRuleList(
							'list',  // action
							1,      // page
							100,    // limit
							this.category,
							this.subcategory,
							'',     // keyword
							''      // creatorId
						);
						
						console.log('获取规则标题列表结果:', res);
						if (res && res.code === 0) {
							console.log('原始数据:', res.data);
							
							// 保存原始数据
							this.originalList = (res.data || []).map(item => ({...item}));
							
							let list = res.data || [];
							
							// 确保每个规则项都有title字段和tags字段
							list = list.map(item => ({
								...item,
								title: item.title || '未命名规则',
								tags: Array.isArray(item.tags) ? item.tags : (item.tags ? [item.tags] : [])
							}));
							
							console.log('处理后的数据:', list);
							
							// 应用排序逻辑
							this.applySort(list);
							
							console.log('排序后的数据:', this.tertiaryList);
						} else {
							uni.showToast({
								title: res?.message || '获取数据失败',
								icon: 'none'
							});
						}
					} catch (err) {
						console.error('获取规则标题列表失败', err);
						uni.showToast({
							title: '网络错误，请稍后重试',
							icon: 'none'
						});
					} finally {
						this.loading = false;
						uni.hideLoading();
					}
				})();
			},
			
			// 应用排序逻辑
			applySort(list) {
				let sortedList = [...list];
				
				if (this.sortOrder === 'asc') {
					// 递增排序：按照上传时间递增
					sortedList.sort((a, b) => {
						const dateA = new Date(a.create_date);
						const dateB = new Date(b.create_date);
						return dateA - dateB; // 时间越早排在前面
					});
				} else if (this.sortOrder === 'custom') {
					// 自定义排序：应用保存的顺序
					try {
						const key = `customOrder_${this.category}_${this.subcategory}`;
						const savedOrder = uni.getStorageSync(key);
						
						if (savedOrder) {
							const orderMap = new Map();
							JSON.parse(savedOrder).forEach(item => {
								orderMap.set(item.id, item.order);
							});
							
							// 应用保存的顺序
							sortedList.sort((a, b) => {
								const orderA = orderMap.has(a._id) ? orderMap.get(a._id) : 999;
								const orderB = orderMap.has(b._id) ? orderMap.get(b._id) : 999;
								return orderA - orderB;
							});
						}
					} catch (e) {
						console.error('读取自定义排序失败', e);
					}
				}
				
				this.tertiaryList = sortedList;
			},
			
			// 更改排序方式
			changeSortOrder(order) {
				if (this.sortOrder === order) return;
				
				this.sortOrder = order;
				
				// 保存排序方式
				try {
					uni.setStorageSync(`sortOrder_${this.category}_${this.subcategory}`, order);
				} catch (e) {
					console.error('保存排序方式失败', e);
				}
				
				// 重新应用排序
				if (this.originalList.length > 0) {
					this.applySort([...this.originalList]);
				} else {
					this.applySort([...this.tertiaryList]);
				}
			},
			
			// 开始拖拽
			startDrag(index) {
				// 自定义排序模式下才允许拖拽
				if (this.sortOrder !== 'custom') {
					uni.showToast({
						title: '请切换到自定义排序模式',
						icon: 'none'
					});
					return;
				}
				
				// 触发震动反馈
				uni.vibrateShort({
					success: () => {
						console.log('震动成功');
					}
				});
				
				// 记录开始拖拽的位置和索引
				this.dragIndex = index;
				
				// 获取当前卡片的大致高度（包括margin）
				// 实际应用中可能需要动态计算
				this.cardHeight = 150; // rpx单位，根据实际卡片高度调整
				
				// 阻止点击事件触发
				this.isDragging = true;
			},
			
			// 触摸移动处理
			onTouchMove(e) {
				if (this.dragIndex === -1 || this.sortOrder !== 'custom') return;
				
				const touch = e.touches[0];
				if (!this.startY) {
					this.startY = touch.clientY;
				}
				
				// 计算拖拽偏移量
				this.dragOffset = touch.clientY - this.startY;
				
				// 计算可能的目标位置
				const targetIndex = Math.round(this.dragIndex + this.dragOffset / this.cardHeight);
				
				// 如果移动足够距离，交换位置
				if (targetIndex !== this.dragIndex && 
					targetIndex >= 0 && 
					targetIndex < this.tertiaryList.length) {
					
					// 交换列表中的项
					const item = this.tertiaryList.splice(this.dragIndex, 1)[0];
					this.tertiaryList.splice(targetIndex, 0, item);
					
					// 更新拖拽索引和起始位置
					this.dragIndex = targetIndex;
					this.startY = touch.clientY;
					this.dragOffset = 0;
					
					// 标记列表已更改
					this.listChanged = true;
				}
			},
			
			// 触摸结束处理
			onTouchEnd() {
				if (this.dragIndex !== -1) {
					// 重置拖拽状态
					this.dragIndex = -1;
					this.startY = 0;
					this.dragOffset = 0;
					
					// 如果列表已更改，保存顺序
					if (this.listChanged && this.sortOrder === 'custom') {
						this.saveCustomOrder();
						this.listChanged = false;
					}
					
					// 延迟一段时间后允许点击，避免拖拽后立即触发点击
					setTimeout(() => {
						this.isDragging = false;
					}, 300);
				}
			},
			
			// 保存自定义顺序
			saveCustomOrder() {
				// 构建排序数据
				const orderData = this.tertiaryList.map((item, index) => ({
					id: item._id,
					title: item.title,
					order: index
				}));
				
				// 保存到本地存储
				try {
					const key = `customOrder_${this.category}_${this.subcategory}`;
					uni.setStorageSync(key, JSON.stringify(orderData));
					console.log('自定义排序已保存', orderData);
					
					// 可选：同步到云端
					// this.syncOrderToCloud(orderData);
				} catch (e) {
					console.error('保存自定义排序失败', e);
				}
			},
			
			// 导航到规则详情页
			navigateToDetail(item) {
				// 如果正在拖拽，不触发点击事件
				if (this.isDragging) return;
				
				if (!item || !item._id) {
					uni.showToast({
						title: '无效的规则内容',
						icon: 'none'
					});
					return;
				}
				
				uni.navigateTo({
					url: `/packageStudy/study/rule-detail?id=${item._id}`,
					fail: (err) => {
						console.error('导航到规则详情页失败', err);
						uni.showToast({
							title: '打开页面失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 生成卡片渐变色 - 使用对应二级标签的颜色
			getCardGradient() {
				// 使用二级标签（subcategory）生成颜色，而不是标题
				if (!this.subcategory) return 'linear-gradient(135deg, #FF9800 0%, #F57C00 100%)'; // 默认渐变色
				
				// 使用简单的哈希算法基于subcategory字符串生成颜色
				let hash = 0;
				for (let i = 0; i < this.subcategory.length; i++) {
					hash = this.subcategory.charCodeAt(i) + ((hash << 5) - hash);
				}
				
				// 使用与study.vue页面相同的渐变色数组，保持一致性
				const gradients = [
					'linear-gradient(135deg, #1BAE76 0%, #0E8A5A 100%)', // 绿色渐变
					'linear-gradient(135deg, #4A90E2 0%, #2171B5 100%)', // 蓝色渐变
					'linear-gradient(135deg, #9C27B0 0%, #7B1FA2 100%)', // 紫色渐变
					'linear-gradient(135deg, #FF9800 0%, #F57C00 100%)', // 橙色渐变
					'linear-gradient(135deg, #F44336 0%, #D32F2F 100%)', // 红色渐变
					'linear-gradient(135deg, #009688 0%, #00695C 100%)', // 青绿色渐变
					'linear-gradient(135deg, #3F51B5 0%, #303F9F 100%)', // 靛蓝色渐变
					'linear-gradient(135deg, #FF5722 0%, #E64A19 100%)', // 深橙色渐变
					'linear-gradient(135deg, #8BC34A 0%, #689F38 100%)', // 浅绿色渐变
					'linear-gradient(135deg, #607D8B 0%, #455A64 100%)', // 蓝灰色渐变
					'linear-gradient(135deg, #E91E63 0%, #C2185B 100%)', // 粉色渐变
					'linear-gradient(135deg, #00BCD4 0%, #0097A7 100%)'  // 青色渐变
				];
				
				// 使用哈希值选择一个渐变色
				const gradientIndex = Math.abs(hash) % gradients.length;
				return gradients[gradientIndex];
			},
			
			// 根据内容标题获取合适的图标
			getContentIcon(title) {
				if (!title) return '📖';
				
				// 根据标题内容特征选择图标
				const titleText = title.toLowerCase();
				
				if (titleText.includes('规则') || titleText.includes('rule')) return '📋';
				if (titleText.includes('第') && titleText.includes('章')) return '📑';
				if (titleText.includes('第') && titleText.includes('条')) return '📄';
				if (titleText.includes('球场') || titleText.includes('场地')) return '🏟️';
				if (titleText.includes('球') && !titleText.includes('球场')) return '⚽';
				if (titleText.includes('队员') || titleText.includes('球员')) return '👥';
				if (titleText.includes('裁判') || titleText.includes('referee')) return '👨‍⚖️';
				if (titleText.includes('犯规') || titleText.includes('违规')) return '⚠️';
				if (titleText.includes('时间') || titleText.includes('计时')) return '⏰';
				if (titleText.includes('开始') || titleText.includes('开球')) return '🚀';
				if (titleText.includes('越位') || titleText.includes('offside')) return '🚫';
				if (titleText.includes('手势') || titleText.includes('信号')) return '✋';
				if (titleText.includes('装备') || titleText.includes('器材')) return '⚙️';
				if (titleText.includes('安全') || titleText.includes('safety')) return '🛡️';
				if (titleText.includes('训练') || titleText.includes('practice')) return '💪';
				if (titleText.includes('技术') || titleText.includes('tech')) return '🔧';
				if (titleText.includes('程序') || titleText.includes('procedure')) return '📝';
				if (titleText.includes('管理') || titleText.includes('manage')) return '📊';
				if (titleText.includes('指南') || titleText.includes('guide')) return '🧭';
				
				// 默认图标
				return '📖';
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		width: 100%;
		box-sizing: border-box;
		padding-bottom: 30rpx;
	}

	/* 头部样式 */
	.header {
		background: linear-gradient(135deg, #1BAE76 0%, #0E8A5A 100%);
		padding: 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(27, 174, 118, 0.25);
		position: relative;
		width: 100%;
		box-sizing: border-box;
		margin-bottom: 20rpx;
	}
	
	.header::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0.08);
		backdrop-filter: blur(8rpx);
		pointer-events: none;
	}
	
	.category-path {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
		position: relative;
		z-index: 1;
	}
	
	.primary-category {
		font-size: 28rpx;
		color: rgba(255, 255, 255, 0.85);
		text-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.2);
	}
	
	.path-separator {
		font-size: 28rpx;
		color: rgba(255, 255, 255, 0.7);
		margin: 0 10rpx;
	}
	
	.secondary-category {
		font-size: 28rpx;
		color: #fff;
		font-weight: bold;
		text-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.2);
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #fff;
		margin-top: 10rpx;
		position: relative;
		z-index: 1;
		text-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.2);
	}

	/* 排序选项样式 */
	.sort-options {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
	}
	
	.sort-label {
		font-size: 26rpx;
		color: #666;
		margin-right: 20rpx;
		font-weight: 500;
	}
	
	.sort-buttons {
		display: flex;
		gap: 12rpx;
	}
	
	.sort-btn {
		padding: 10rpx 24rpx;
		font-size: 24rpx;
		color: #666;
		background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
		border-radius: 20rpx;
		transition: all 0.3s ease;
		border: 1rpx solid rgba(0, 0, 0, 0.08);
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.08);
	}
	
	.sort-btn.active {
		background: linear-gradient(135deg, #FF9800 0%, #F57C00 100%);
		color: #fff;
		border: 1rpx solid rgba(255, 152, 0, 0.3);
		box-shadow: 0 4rpx 12rpx rgba(255, 152, 0, 0.3);
		transform: translateY(-1rpx);
	}

	/* 规则标题卡片列表样式 */
	.tertiary-list {
		padding: 0 30rpx;
		width: 100%;
		box-sizing: border-box;
	}

	.tertiary-card {
		background: linear-gradient(135deg, #FF9800 0%, #F57C00 100%); /* 默认渐变背景，会被内联样式覆盖 */
		border-radius: 20rpx;
		overflow: hidden;
		margin-bottom: 24rpx;
		box-shadow: 0 6rpx 28rpx rgba(0, 0, 0, 0.12), 0 3rpx 14rpx rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
		position: relative;
		backdrop-filter: blur(8rpx);
	}
	
	.tertiary-card:active {
		transform: scale(0.98);
	}
	
	.tertiary-card::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0.08);
		backdrop-filter: blur(6rpx);
		pointer-events: none;
	}
	
	/* 拖拽状态样式 */
	.tertiary-card.is-dragging {
		box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.18), 0 6rpx 20rpx rgba(0, 0, 0, 0.12);
	}
	
	.card-content {
		position: relative;
		z-index: 1;
		padding: 24rpx;
	}

	.card-header {
		display: flex;
		align-items: center;
		margin-bottom: 12rpx;
	}
	
	.card-icon {
		font-size: 32rpx;
		margin-right: 12rpx;
		opacity: 0.9;
		text-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.2);
	}
	
	.card-title-wrapper {
		flex: 1;
	}

	.card-title {
		font-size: 30rpx;
		color: #FFFFFF;
		font-weight: bold;
		line-height: 1.4;
		text-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.2);
	}
	
	.card-meta {
		display: flex;
		align-items: center;
		margin-top: 12rpx;
		flex-wrap: wrap;
		gap: 12rpx;
	}
	
	.card-tags {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 8rpx;
	}
	
	.card-tag {
		font-size: 20rpx;
		color: #FFFFFF;
		background: rgba(255, 255, 255, 0.22);
		padding: 4rpx 12rpx;
		border-radius: 16rpx;
		backdrop-filter: blur(4rpx);
		border: 1rpx solid rgba(255, 255, 255, 0.15);
	}
	
	.card-views {
		font-size: 22rpx;
		color: rgba(255, 255, 255, 0.85);
		margin-left: auto;
	}
	
	/* 空状态样式 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}
	
	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
</style> 